﻿using CoreShop.Library;
using CoreShop.Model;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CoreShop.App
{
    public class SigangUtil
    {
        private corecmsscale scaleModel = new corecmsscale();
        private List<corecmsfood> goodsList = new List<corecmsfood>();

        public int GetPortFromIP(string szIPAddr)
        {
            string[] segments = szIPAddr.Split('.');
            if (segments != null && segments.Length >= 4)
            {
                return 2000 + Int32.Parse(segments[3]);
            }
            return 0;
        }

        //将string的值赋给Bytes
        private void SetBytes(byte[] dstbyt, string srcstr)
        {
            byte[] tempbyt = Encoding.Default.GetBytes(srcstr);
            System.Buffer.BlockCopy(
                tempbyt,
                0,
                dstbyt,
                0,
                Math.Min(tempbyt.Length, dstbyt.Length)
            );
        }

        public void SendToScales_SG(string IPADDR, corecmsscale _scaleModel, List<corecmsfoodspec> _goodsList)
        {
            Int32 IPPORT = 0;
            Int32 socks;
            int iPlu;
            PluFIle labelPLU;
            Int32 commResult;
            String itemcode;
            IPPORT = GetPortFromIP(IPADDR);
            //根据IP地址连接电子称，端口号为IP地址末个字段前面加上2，如下
            socks = DllCall.Connect(IPADDR, IPPORT);
            if (socks <= 0)
            {
                string msg = "电子称【" + IPADDR + "】连接错误，无法下传！";
                MessageBox.Show(msg);
                return;
            }

            string sTemp = "";
            int iTemp = 0;            
            foreach (var item in goodsList)
            {
                labelPLU = new PluFIle();
                //结构体初始化
                labelPLU.Initialize();

                //品项PLU，最大6位
                //==labelPLU.PLUNo = 321000 + i;
                sTemp = item.number;
                if (sTemp.Length < 7) continue;
                sTemp = sTemp.Substring(sTemp.Length - 5);
                iPlu = Convert.ToInt32(sTemp);
                labelPLU.PLUNo = iPlu;

                //称重标志－0:计重;1:计件
                //labelPLU.WeightUnit = 0;
                int iWeightUnit = 0;
                if (item.stand == (int)GlobalEnumVars.stand.Count) iWeightUnit = 1;
                labelPLU.WeightUnit = iWeightUnit;

                //允许单价覆盖标志－0:禁止;1:允许
                labelPLU.UPriceOverride = 0;
                //单价信息
                sTemp = Math.Floor(item.posPrice * 100).ToString();
                labelPLU.UPrice = Convert.ToInt32(sTemp);
                //标签格式编号，从17开始，对应于称上的编号
                labelPLU.LabelFormat1 = 17;
                //条码格式编号，具体含义和信息需参考相应文档
                labelPLU.BarFormat = 5;
                //店内码头标志F1F2，以下是以28打头
                //labelPLU.EANFlags = 21;
                labelPLU.EANFlags = AppConstVars.systemsetup.weighingCodeSign.ObjToInt(21);

                //品项店内码信息，请设置为固定10位
                //itemcode = String.Format("{0}", labelPLU.PLUNo - 300000);
                //itemcode = String.Format("{0}", labelPLU.PLUNo *100000);
                //if (itemcode.Length < 10)
                //    itemcode += new string('0', 10 - itemcode.Length);
                sTemp = item.number;
                itemcode = sTemp.Substring(sTemp.Length - 5) + "00000";
                //SetBytes(labelPLU.EAN_Data.ItemCode, "1255300000");
                SetBytes(labelPLU.EAN_Data.ItemCode, itemcode);
                string sss = String.Format("{0:3}", 9);
                //条码类型－9:ITF;0:EAN
                labelPLU.EAN_Data.BarCodeType = 0;
                //条码右侧数据，具体含义和信息需参考相应文档
                labelPLU.EAN_Data.BarRightData = 1;
                //主组编号
                labelPLU.MG = 997;
                //售出日期(天数)
                labelPLU.SBDate = 0;
                //保质日期(天数)
                //labelPLU.UBDate = 20 + i;
                iTemp = item.warrantyValue.ObjToInt(0);
                labelPLU.UBDate = iTemp;
                //特殊信息
                labelPLU.SPMessage[0].TwsFontSize = 20;
                SetBytes(labelPLU.SPMessage[0].TxtValue, "");

                //成份信息
                for (int j = 0; j < 3; j++)
                {
                    labelPLU.Ingredient[j].TwsFontSize = 20;
                    if (j == 1)
                    {
                        SetBytes(labelPLU.Ingredient[j].TxtValue, "");
                    }
                    else
                        SetBytes(labelPLU.Ingredient[j].TxtValue, String.Format("成份{0}", j + 1));

                }

                labelPLU.Discount.StartDate = 240714;   //开始日期:DDMMYY
                labelPLU.Discount.EndDate = 250714;     //结束日期:DDMMYY
                labelPLU.Discount.StartTime = 1400;     //开始时间:HHMM
                labelPLU.Discount.EndTime = 1500;       //结束时间:HHMM
                labelPLU.Discount.DisType = 3;	        //打折类型，请参考digi2005中的数字
                labelPLU.Discount.MarkDown = 1;	        //标志类型，请参考digi2005中的数字
                labelPLU.Discount.FirstLIM = 200;       //打折范围1
                labelPLU.Discount.SecondLIM = 300;      //打折范围2
                labelPLU.Discount.Within1stLIM = 1000;  //打折额度1(10%)
                labelPLU.Discount.Within2ndLIM = 2000;  //打折额度2(20%)


                //品项字体大小
                labelPLU.Commodity[0].TwsFontSize = 21;
                //品项名称，最大100位
                SetBytes(labelPLU.Commodity[0].TxtValue, item.name.ToString());

                //设置多重条码
                //labelPLU.MBarcode1.MutilBarFunc = 86;
                //SetBytes(labelPLU.MBarcode1.MutilBarData, "F (94)XXXXXXXXXXXXXXXXXXXXXXXXXXCD");
                //labelPLU.MBarcode1.MutilBarType = 2;

                //发送品项信息到接口程序
                int iiaa = Marshal.SizeOf(labelPLU);
                commResult = DllCall.SendLabelPLU(socks, ref labelPLU);
                //返回值等于6才是正常的，否则退出或自行处理
                if (commResult != 6)
                    break;

                Application.DoEvents();
            }

            Application.DoEvents();

            //断开与称之间的连接
            DllCall.Disconnect(socks);
            MessageBox.Show("下传完成!");
        }

    }
}
